package com.ruoyi.common.security.interceptor;

import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.lang.Nullable;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
/**
 * Author:cgChen
 * Date:2022/05/13 9:37
 * Description:重载Request参数
 */
public class ParameterRequestWrapper extends HttpServletRequestWrapper{
    private Map params = new HashMap<>();
    public ParameterRequestWrapper(HttpServletRequest request) {
        super(request);
        //将参数表，赋予给当前的Map以便于持有request中的参数
        this.params.putAll(request.getParameterMap());

        setHeaderMap(request);
//此处可以对数据做任何修改后，再放入到body
        String dataInfo = request.getParameter("data");
        if (StringUtils.isEmpty(dataInfo)) {
            return;
        }
        ByteArrayInputStream delegate = new ByteArrayInputStream(dataInfo.getBytes(StandardCharsets.UTF_8));
        body = new ServletInputStream() {
            @Override
            public int read() {
                return delegate.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {
                throw new UnsupportedOperationException();
            }
        };
    }
    /**

     * 重载构造方法

     */

    public ParameterRequestWrapper(HttpServletRequest request, Map extendParams) {

        this(request);

//这里将扩展参数写入参数表

        addAllParameters(extendParams);

    }

    /**

     * 在获取所有的参数名,必须重写此方法，否则对象中参数值映射不上

     *

     * @return

     */

    @Override

    public Enumeration getParameterNames() {

        return new Vector(params.keySet()).elements();

    }

    /**

     * 重写getParameter方法

     *

     * @param name 参数名

     * @return 返回参数值

     */

    @Override

    public String getParameter(String name) {

        String[] values = (String[]) params.get(name);

        if (values == null || values.length == 0) {

            return null;

        }

        return values[0];

    }

    @Override

    public String[] getParameterValues(String name) {

        String[] values = (String[]) params.get(name);

        if (values == null || values.length == 0) {

            return null;

        }

        return values;

    }

    /**

     * 增加多个参数

     *

     * @param otherParams 增加的多个参数

     */

    public void addAllParameters(Map otherParams) {
        for (Object entry1 : otherParams.entrySet()) {
            Map.Entry entry= (Map.Entry) entry1;
            addParameter(entry.getKey().toString(), entry.getValue());

        }
    }

    /**
     * 增加参数
     *
     * @param name 参数名
     * @param value 参数值
     */
    public void addParameter(String name, Object value) {
        if (value != null) {
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if (value instanceof String) {
                params.put(name, new String[]{(String) value});
            } else {
                params.put(name, new String[]{String.valueOf(value)});
            }
        }
    }

    private final String contentType = "application/json";

    private Map<String, String> headerMap = new HashMap<>();

    @Nullable
    private ServletInputStream body;


    @Override
    public ServletInputStream getInputStream() {
        return body;
    }

    /**
     * add a header with given name and value
     */
    private void addHeader(String name, String value) {
        headerMap.put(name, value);
    }

    @Override
    public String getHeader(String name) {
        String headerValue = super.getHeader(name);
        if (headerMap.containsKey(name)) {
            headerValue = headerMap.get(name);
        }
        return headerValue;
    }

    /**
     * get the Header names
     */
    @Override
    public Enumeration<String> getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        names.addAll(headerMap.keySet());
        return Collections.enumeration(names);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        List<String> values = Collections.list(super.getHeaders(name));
        if (headerMap.containsKey(name)) {
            values = Collections.singletonList(headerMap.get(name));
        }
        return Collections.enumeration(values);

    }

    private void setHeaderMap(HttpServletRequest request) {
        Enumeration e = request.getHeaderNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            String value = request.getHeader(name);
            addHeader(name, value);
        }
        addHeader("content-type", contentType);
    }

    public String getContentType(){
        return contentType;
    }
}
